package cn.xiehang.SoundSight;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class AccountSettingFragment extends Fragment {
    private static final int REQUEST_CODE_IMAGE_PICK = 1001;
    private static final int REQUEST_CODE_PERMISSION = 1002;
    String getUserURL=SeverURL.URL+"/get_user_info";
    String getProfilePictureURL=SeverURL.URL+"/get_profile_photo/";
    Button change_photo_button;
    ImageView user_avatar;
    String SetProfilePictureURL=SeverURL.URL+"/save_profile_photo";
    User user;
    Button reset_username_button;
    EditText reset_username;

    private File imageFile;


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_account_setting, container, false);
        // 初始化视图组件
        initView(view);
        // 绑定事件
        bindingEvents();
        // 初始化用户信息
        initUserInfo();

        return view;
    }
    public void onResume() {
        super.onResume();
        // 重新获取用户信息
        initUserInfo();
    }
    private void initView(View view){
        change_photo_button = view.findViewById(R.id.change_photo_button);
        user_avatar = view.findViewById(R.id.profile_image);
        reset_username = view.findViewById(R.id.username_input);
        reset_username_button = view.findViewById(R.id.reset_username_button);

    }
    private void bindingEvents() {
        // 绑定事件
        change_photo_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(requireContext(),
                        android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            REQUEST_CODE_PERMISSION);
                } else {
                    openFilePicker();
                }

            }
        });
        reset_username_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入的用户名
                String newUsername = reset_username.getText().toString().trim();
                // 检查用户名是否为空
                if (newUsername.isEmpty()) {
                    Toast.makeText(requireContext(), "请输入新的用户名", Toast.LENGTH_SHORT).show();
                    return;
                }
                // 显示等待弹窗
                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());

                reset_username_button.setEnabled(false);

                // 发送请求修改用户名
                SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
                String username = sharedPref.getString("username", null);
                String password = sharedPref.getString("password", null);

                // 创建 OkHttpClient 实例
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                JSONObject jsonBody = new JSONObject();
                try {
                    jsonBody.put("username", username);
                    jsonBody.put("password", password);
                    jsonBody.put("reset_username", newUsername);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                // 构建 RequestBody
                RequestBody requestBody = RequestBody.create(
                        jsonBody.toString(),
                        MediaType.parse("application/json; charset=utf-8")
                );
                // 创建请求
                Request request = new Request.Builder()
                        .url(SeverURL.URL + "/reset_username")
                        .post(requestBody)
                        .addHeader("Content-Type", "application/json")
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        requireActivity().runOnUiThread(() -> {
                            builder.setMessage("error: " + e.getMessage());
                            builder.setPositiveButton("确定", (dialog, which) -> dialog.dismiss());
                            builder.show();
                            reset_username_button.setEnabled(true);
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        try {
                            String responseData = response.body().string();
                            JSONObject jsonResponse = new JSONObject(responseData);
                            String message = jsonResponse.getString("message");

                            requireActivity().runOnUiThread(() -> {
                                // 更新SharedPreferences中的用户名
                                SharedPreferences.Editor editor = sharedPref.edit();
                                editor.putString("username", newUsername);
                                editor.apply();

                                builder.setMessage(message);
                                builder.setPositiveButton("确定", (dialog, which) -> {
                                    reset_username.setText("");
                                    // 刷新用户信息
                                    initUserInfo();
                                });
                                builder.show();
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                            requireActivity().runOnUiThread(() -> {
                                builder.setMessage("解析数据出错");
                                builder.setPositiveButton("确定", (dialog, which) -> dialog.dismiss());
                                builder.show();
                            });
                        } finally {
                            requireActivity().runOnUiThread(() -> {
                                reset_username_button.setEnabled(true);
                            });
                        }
                    }
                });
            }
        });
    }

    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*"); // 选择音频文件
        // 确保有应用可以处理这个Intent
        if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_CODE_IMAGE_PICK);
        } else {
            Toast.makeText(requireContext(), "没有可用的文件管理器", Toast.LENGTH_SHORT).show();
        }
    }
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_IMAGE_PICK && resultCode == Activity.RESULT_OK && data != null) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    imageFile =  uriToFile(uri);
                    up_profile();
                }
            }
        }
    }
    private void up_profile() {
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);

        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return;
        }
// 获取用户ID
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);

        // 1. 创建 OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();





        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", username)
                .addFormDataPart("password", password)
                .addFormDataPart("image", imageFile.getName(),
                        RequestBody.create(MediaType.parse("image/*"), imageFile))
                .build();
        // 2. 创建请求
        Request request = new Request.Builder()
                .url(SetProfilePictureURL)
                .post(requestBody)
                .build();
        // 3. 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败情况
                requireActivity().runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("上传头像出错")
                            .setMessage("error: " + e.getMessage())
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }
                String responseData = response.body().string();
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireContext(), "头像上传成功", Toast.LENGTH_SHORT).show();

                    initUserInfo();
                });
            }
        });
    }
    private void initUserInfo() {
        // 初始化数据
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("username", username);
            jsonBody.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 构建 RequestBody
        RequestBody requestBody = RequestBody.create(
                jsonBody.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );
        // 创建请求
        Request request = new Request.Builder()
                .url(getUserURL)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败情况
                requireActivity().runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("获取用户信息出错")
                            .setMessage("error: " + e.getMessage())
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                String responseData = response.body().string();

                try {
                    // 解析JSON数据
                    JSONObject jsonResponse = new JSONObject(responseData);
                    // 获取各字段值
                    String username = jsonResponse.getString("username");
                    String level = String.valueOf(jsonResponse.getInt("user_level")); // 将数字转为字符串
                    String avatar = jsonResponse.isNull("avatar") ? null : jsonResponse.getString("avatar"); // 处理null值
                    // 创建User对象
                    user = new User(username, avatar, level);

                    requireActivity().runOnUiThread(() -> {
                        // 更新UI
                        // 这里可以更新UI组件，例如设置用户名和头像
                        updateUI(user);
                    });


                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                        builder.setTitle("解析数据出错")
                                .setMessage("error: " + e.getMessage())
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 关闭对话框
                                    dialog.dismiss();
                                })
                                .show();
                    });
                }
            }
        });
    }
    private void updateUI(User user) {
        if (isAdded()) { // 检查Fragment是否附加到Activity
            if (user.getProfilePictureUrl() != null && !user.getProfilePictureUrl().isEmpty()) {
                Glide.with(requireContext())
                        .load(getProfilePictureURL+user.getProfilePictureUrl())
                        .placeholder(R.drawable.ic_fourth_normal) // 加载中的占位图
                        .error(R.drawable.ic_fourth_normal)     // 加载失败的错误图
                        .into(user_avatar);
            } else {
                // 当avatar为null时，加载默认头像
                user_avatar.setImageResource(R.drawable.ic_fourth_normal);
            }
        }

    }
    private File uriToFile(Uri uri) {
        // 先尝试直接获取路径
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            return new File(uri.getPath());
        }

        // 对于content:// Uri，需要复制到缓存目录
        String fileName = getFileNameFromUri(uri);
        if (fileName == null) {
            fileName = "image_" + System.currentTimeMillis();
        }

        File cacheDir = requireContext().getCacheDir();
        File outputFile = new File(cacheDir, fileName);

        try (InputStream in = requireContext().getContentResolver().openInputStream(uri);
             OutputStream out = new FileOutputStream(outputFile)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            return outputFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    private String getFileNameFromUri(Uri uri) {
        String displayName = "image_" + System.currentTimeMillis(); // 默认文件名

        // 先尝试通过DISPLAY_NAME列获取
        try (Cursor cursor = requireContext().getContentResolver().query(
                uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                // 安全获取列索引
                int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                if (nameIndex >= 0) {
                    displayName = cursor.getString(nameIndex);
                } else {
                    // 如果DISPLAY_NAME列不存在，尝试其他方式
                    displayName = getFileNameFallback(uri, cursor);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return displayName;
    }
    private String getFileNameFallback(Uri uri, Cursor cursor) {
        // 方案1：尝试从URI最后一段获取
        String fileName = uri.getLastPathSegment();
        if (fileName != null && !fileName.isEmpty()) {
            // 去除可能包含的路径部分
            int cut = fileName.lastIndexOf('/');
            if (cut != -1) {
                fileName = fileName.substring(cut + 1);
            }
            return fileName;
        }

        // 方案2：遍历所有列尝试找到文件名
        for (String columnName : cursor.getColumnNames()) {
            if (columnName.toLowerCase().contains("name") ||
                    columnName.toLowerCase().contains("display")) {
                int index = cursor.getColumnIndex(columnName);
                if (index >= 0) {
                    String name = cursor.getString(index);
                    if (name != null && !name.isEmpty()) {
                        return name;
                    }
                }
            }
        }
        // 方案3：使用数据列作为最后手段
        int dataIndex = cursor.getColumnIndex("_data");
        if (dataIndex >= 0) {
            String path = cursor.getString(dataIndex);
            if (path != null) {
                return new File(path).getName();
            }
        }

        // 所有方案都失败，返回默认名称
        return "image_" + System.currentTimeMillis();
    }
}
